$LOAD_PATH.unshift File.join(File.dirname(__FILE__),'../..','ext_pr1/lib')
require 'ext_pr1_v4'

# Clock
# Digitalclock with options to update the min, sec and hours
# The clock returns a array and shows in 12 or 24 hours mode
#
# add_clock ::= (act_clock, delta, mode) ::
# set of array [int,int,int] x [int,int,int] x bool => [int,int,int]
# array [hours,minutes,seconds] bool false = 24h mode, true = 12h mode
#
# examples
# set_clock([0,0,0],[1,1,1],false) => [1,1,1]
# set_clock([0,0,0],[23,59,59],false) => [23,59,59]
# set_clock([0,0,1],[23,59,59],false) => [0,0,0]
# set_clock([0,0,0],[12,1,1),true) => [0,1,1]

# Constants
def seconds_per_minute() 60 end
def minutes_per_hours() 60 end
def hours_per_day() 24 end
def hours_per_halfday() hours_per_day / 2 end

# calc the new time
def add_clock(act_clock, delta_clock, mode)
   # precondition checks
   check_pre((act_clock.array? and delta_clock.array? and
              act_clock.size==3 and delta_clock.size==3 and
              act_clock[0].nat? and act_clock[1].nat? and act_clock[2].nat? and
              delta_clock[0].int? and delta_clock[1].int? and delta_clock[2].int? and
              act_clock[0]<hours_per_day and act_clock[1]<minutes_per_hours() and act_clock[2]<seconds_per_minute() and
              act_clock[0]>=0 and act_clock[1]>=0 and act_clock[2]>=0 and
              mode.bool?))

   # adding the time
   sec = add_time(act_clock[2], delta_clock[2],seconds_per_minute)
   min = add_time(act_clock[1]+sec[0],delta_clock[1],minutes_per_hours)
   h   = add_time(act_clock[0]+min[0],delta_clock[0], mode ? hours_per_halfday : hours_per_day)

   # returing the time
   [h[1],min[1],sec[1]]
end

def add_time(actual, delta, max)
   # precondition checks
   check_pre((actual.int? and delta.int? and max.int?))
   # calculate and returing the time
   (actual+delta).divmod(max)
end